<?php if ( ! defined("BASEPATH")) exit("No direct script access allowed");

class PollsModel extends CI_Model {

    function getPollOptions($id) {
        $this->db->select("*");
        $this->db->from("poll_options");
        $this->db->where("poll_id", $id);

		$query = $this->db->get();
		$result = $query->result();

		return $result;
    }

    function getPollOptionsIncludingVoteCount($id) {
        $this->db->select("*, count(user_poll_options.poll_option_id) as vote_count");
        $this->db->from("poll_options");
        $this->db->join("user_poll_options", "poll_options.id = user_poll_options.poll_option_id", "left");
        $this->db->where("poll_options.poll_id", $id);
        $this->db->group_by("poll_options.id");

		$query = $this->db->get();
		$result = $query->result();

		return $result;
    }

    function registerVote($user_id, $option_id) {
        $data = array("user_id" => $user_id,
                      "poll_option_id" => $option_id);
        $this->db->insert("user_poll_options", $data);
    }

    function didUserVote($user_id, $poll_id) {
        $this->db->select("*");
        $this->db->from("user_poll_options");
        $this->db->join("poll_options", "user_poll_options.poll_option_id = poll_options.id");
        $this->db->where("poll_options.poll_id", $poll_id);
        $this->db->where("user_poll_options.user_id", $user_id);

        $query = $this->db->get();
		$result = $query->result();

        return (count($result) > 0);

    }

    public function addPoll($question, $answers){
        $user_id = $this->tank_auth->get_user_id();

        $data = array("topic" => $question);
        $this->db->insert("polls", $data);
        $poll_id = $this->db->insert_id();

        $this->db->flush_cache();

        foreach($answers as $answer){
            if($answer != ""){
                $data = array("answer" => $answer, "poll_id" =>$poll_id);
                $this->db->insert("poll_options", $data);

                 $this->db->flush_cache();
            }
        }


        $this->load->model('PostsModel');
        $this->PostsModel->insertPost("poll", $poll_id, $user_id);
    }

    public function addPollOptionsToPosts($posts) {
        foreach ($posts as $post) {
            if ($post->type == "poll") {
                $id = $post->poll_id;

                $user_id = $this->tank_auth->get_user_id();
                $post->voted = $this->didUserVote($user_id, $id);

                if ($post->voted) {
                    $post->options = $this->getPollOptionsIncludingVoteCount($id);
                } else {
                    $post->options = $this->getPollOptions($id);
                }
            }
        }

        return $posts;
    }
}

